///新版本
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_ahj_app/app/NewMine/AccountViewModel.dart';
import 'package:flutter_ahj_app/base/utils/JUIKit/JText.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';
import 'package:flutter_ahj_app/base/widget/LoadingWidget.dart';

import '../../../base/basewidget/view/BaseWidget.dart';

class SureYouView extends BaseStatefulWidget {
  @override
  State<StatefulWidget> initState() {
    // TODO: implement initState
    return SureYouViewState();
  }
}

class SureYouViewState extends BaseState<AccountViewModel, SureYouView> {
  TextEditingController _phoneCtr = TextEditingController();
  TextEditingController _sendmesCtr = TextEditingController();
  String _checkText = "获取验证码";
  Timer countDownTimer; //获取验证码计时器

  Widget _rbGetCheck;
  var _data;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    countDownTimer?.cancel(); //如果已存在先取消置空
    countDownTimer = null;
    Future.delayed(Duration.zero, () {
      _getData();
    });
  }

  _getData() {
    viewModel.getUserInfo();
    viewModel.getUserInfoDataStream().listen((event) {
      if (event['code'] == '0') {
        setState(() {
          _data = event['data'];
          _phoneCtr.text = _data['phone'];
        });
      } else {
        ToastUtils.showToast(event['msg']);
      }
    }, onError: (e) {
      print(e);
    });
  }

  @override
  Widget initWidget() {
    // TODO: implement initWidget

    _rbGetCheck = Container(
      padding: EdgeInsets.fromLTRB(0, 10, 0, 0),
      child: RaisedButton(
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(Dimens.dimens8))),
        child: new Container(
          alignment: Alignment.center,
          child: Text(
            _checkText,
            maxLines: 1,
            style: new TextStyle(
                fontSize: Dimens.textSize28,
                color:
                    _checkText == "获取验证码" ? SQColor.white : SQColor.per60Black),
          ),
        ),
        color: SQColor.theme_color,
        textColor: SQColor.white,
        disabledColor: SQColor.per12Black,
        disabledTextColor: SQColor.white,
        onPressed: _checkText == "获取验证码" ? () => _getCheckCode() : null,
      ),
    );

    return new Scaffold(
      backgroundColor: SQColor.theme_Bg_color,
      appBar: new AppBar(
        centerTitle: true,
        elevation: 0,
        backgroundColor: SQColor.theme_color,
        title: JText(
          '验证身份',
          color: SQColor.white,
          fontSize: 18,
        ),
      ),
      body: _data == null ? LoadingWidget() : _bodyView(),
    );
  }

  _bodyView() {
    return SingleChildScrollView(
      child: Column(
        children: <Widget>[
          _topContent(),
        ],
      ),
    );
  }

  _topContent() {
    return Column(
      children: [
        SizedBox(
          height: Dimens.dimens14,
        ),
        Container(
          margin:
              EdgeInsets.only(left: Dimens.dimens14, right: Dimens.dimens14),
          decoration: BoxDecoration(
            color: SQColor.white,
            borderRadius: BorderRadius.all(Radius.circular(4.0)),
          ),
          child: Column(
            children: [
              Row(
                children: [
                  SizedBox(
                    width: Dimens.dimens14,
                  ),
                  Text("*", style: TextStyle(color: SQColor.red)),
                  Expanded(
                    child: _phoneView(),
                  )
                ],
              ),
              Container(
                height: 1.0,
                color: SQColor.lightGray1,
                margin: EdgeInsets.only(
                    left: Dimens.dimens16, right: Dimens.dimens16),
              ),
              Row(
                children: [
                  SizedBox(
                    width: Dimens.dimens14,
                  ),
                  Text("*", style: TextStyle(color: SQColor.red)),
                  Expanded(
                    child: _sendMsgView(),
                  ),
                  Container(
                    padding: EdgeInsets.only(right: Dimens.dimens12),
                    child: _rbGetCheck,
                  )
                ],
              ),

            ],
          ),
        ),
        _sureBtnContent()
      ],
    );
  }

  _phoneView() {
    return Container(
      alignment: Alignment.center,
      child: TextField(
          controller: _phoneCtr,
          readOnly: true,
          style: TextStyle(fontSize: Dimens.textSize28, color: Color(0xff999999)),
          decoration: InputDecoration(
            icon: JText(
              '手机号:',
              color: SQColor.black_333333,
            ),
            hintText: '请输入手机号',
            hintStyle: TextStyle(fontSize: 15, color: Color(0xffBFBFBF)),
            border: InputBorder.none,
          )),
      height: 54,
      padding: EdgeInsets.only(right: Dimens.dimens14),
    );
  }

  _sendMsgView() {
    return Container(
      alignment: Alignment.center,
      child: TextField(
          inputFormatters: [
            LengthLimitingTextInputFormatter(6),
            FilteringTextInputFormatter.allow(RegExp("[0-9]")),
          ],
          controller: _sendmesCtr,
          decoration: InputDecoration(
            icon: JText(
              '验证码:',
              color: SQColor.black_333333,
            ),
            hintText: '请输入验证码',
            hintStyle: TextStyle(fontSize: 15, color: Color(0xffBFBFBF)),
            border: InputBorder.none,
          )),
      height: 54,
      padding: EdgeInsets.only(right: Dimens.dimens14),
    );
  }

  _sureBtnContent() {
    return InkWell(
      child: Container(
        margin: EdgeInsets.fromLTRB(14, 20, 14, 0),
        decoration: BoxDecoration(
          color: SQColor.theme_color,
          borderRadius: BorderRadius.all(Radius.circular(4.0)),
        ),
        child: Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              JText(
                '下一步',
                color: SQColor.white,
                fontSize: 16,
                fontWeight: FontWeight.w500,
              )
            ],
          ),
        ),
        height: 48,
      ),
      onTap: () {
        _checkCode();
      },
    );
  }

  _checkCode() {
    if (_sendmesCtr.text.isEmpty) {
      ToastUtils.showToast('请输入验证码');
      return;
    }
    var map = {
      'phone': _phoneCtr.text,
      'phoneCaptcha': _sendmesCtr.text
    };
    viewModel.checkCode(map);
    viewModel.checkCodeDataStream().listen((event) {
      if (event['code'] == '0') {
        Navigator.pushNamed(context, "/ResetPswdView", arguments: map);
      } else {
        ToastUtils.showToast(event['msg']);
      }
    }, onError: (e) {
      print(e);
    });
  }

  // 获取验证码
  _getCheckCode() {
    ///判断手机号
    RegExp exp = RegExp('^^(1[3-9])\\d{9}\$');
    bool matched = exp.hasMatch(_phoneCtr.text);
    if (!matched) {
      setState(() {
        ToastUtils.showToast('请输入正确格式的手机号');
      });
      return;
    }

    countDownTimer?.cancel(); //如果已存在先取消置空
    countDownTimer = null;
    setState(() {
      _checkText = "60秒";
    });
    countDownTimer = new Timer.periodic(new Duration(seconds: 1), (t) {
      setState(() {
        if (60 - t.tick > 0) {
          //60-t.tick代表剩余秒数，如果大于0，设置yzmText为剩余秒数，否则重置yzmText，关闭countTimer
          _checkText = "${60 - t.tick}秒";
        } else {
          _checkText = '获取验证码';
          countDownTimer.cancel();
          countDownTimer = null;
        }
      });
    });

    var map = {
      'phone': _phoneCtr.text
    };
    viewModel.getCode(map);
    viewModel.getCodeDataStream().listen((event) {
      if (event['code'] == '0') {
        ToastUtils.showToast('验证码发送成功，请注意查收');
      } else {
        ToastUtils.showToast(event['msg']);
      }
    }, onError: (e) {
      print(e);
    });
  }
}
